<template>
  <div class="app-container">
    <el-card class="box-card" v-if="workorderInfo.status !== '已完成'">
      <div class=" flex justify-end">
        <el-button v-if="workorderInfo.status === '准备中'" plain
                   type="primary" icon="el-icon-video-play"
                   @click="handleContinue" style="margin-left: 8px">开始
        </el-button>

        <div v-if="workorderInfo.status === '进行中'" style="display: inline-block;margin-left: 8px">
          <el-popconfirm
            title="确定完成吗？"
            @confirm="handleComplete"
          >
            <el-button slot="reference" plain type="success" icon="el-icon-finished"
                       v-hasPermi="['develop:workorder:finish']"
            >完成
            </el-button>
          </el-popconfirm>
        </div>
      </div>
    </el-card>
    <el-row :gutter="20">
      <el-col :span="device === 'mobile' ? 24 : 12">
        <div class="grid-content bg-purple">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>工单信息</span>
            </div>
            <div class=" cus_text">
              <div class="flex">
                <span>工单类型</span>
                <span class="flex-1">：{{ workorderInfo.type }}</span>
              </div>
              <div class="flex">
                <span>工单来源</span>
                <span class="flex-1">：{{ workorderInfo.source }}</span>
              </div>
              <div class="flex">
                <span>项目名称</span>
                <span class="flex-1">：{{ workorderInfo.projectName }}</span>
              </div>
              <div class="flex">
                <span>采购单位</span>
                <span class="flex-1">：{{ workorderInfo.name }}</span>
              </div>
              <div class="flex">
                <span>联系人</span>
                <span class="flex-1">：{{ workorderInfo.contactName }}</span>
              </div>
              <div class="flex items-center">
                <span>工单状态</span>
                <div class="flex-1 flex">
                  ：<dict-tag :options="dict.type.sys_edu_order_status" :value="workorderInfo.status"/>
                </div>
              </div>
            </div>
          </el-card>

          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>负责人信息</span>
            </div>
            <div class=" cus_text">
              <div class="flex">
                <span>计划完成时间</span>
                <span class="flex-1 flex items-center">：{{ workorderInfo.planTime }}</span>
              </div>
              <div class="flex" v-if="workorderInfo.principalName">
                <span>负责人</span>
                <span class="flex-1">：{{ workorderInfo.principalName }}</span>
              </div>
              <div class="flex" v-if="workorderInfo.synergyName">
                <span>协同人</span>
                <span class="flex-1">：{{ workorderInfo.synergyName }}</span>
              </div>
              <div class="flex" v-if="workorderInfo.finishTime">
                <span>完成时间</span>
                <span class="flex-1 flex items-center">：{{ workorderInfo.finishTime }}</span>
              </div>
            </div>
          </el-card>

          <el-card v-if="workorderInfo.projectId">
            <div slot="header" class="clearfix">
              <span>项目信息</span>
            </div>
            <div class=" cus_text">
                <Order :project-info="{ ...workorderInfo, id: workorderInfo.projectId }" :type="0"/>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="device === 'mobile' ? 24 : 12">
        <div class="grid-content bg-purple">
          <el-card class="box-card">
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
              <el-tab-pane label="工作日志" name="1">
                  <WorkLog :workorder="workorderInfo"/>
              </el-tab-pane>
              <el-tab-pane label="问题汇总" name="2">
                  <ProblemSummary :workorder="workorderInfo"/>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <el-dialog title="执行人" :visible.sync="userVisible" width="800px" :close-on-press-escape="false" destroy-on-close
               close-on-click-modal :fullscreen="device === 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="demo-form"
               :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="负责人" prop="principalId">
              <el-select v-model="form.principalId" allow-create clearable filterable placeholder="请选择负责人"
                         style="width: 100%;">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="协同人" prop="synergyIds">
              <el-select v-model="form.synergyIds" multiple allow-create clearable filterable placeholder="请选择协同人"
                         style="width: 100%;">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUpload('formRef')">确定</el-button>
        <el-button @click="userVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getDataListApi, updateDataApi} from "@/api/after/workorder";
import {getUserProfile, listUser} from "@/api/system/user";
import {getDataListApi as getDataInfoApi} from "@/api/components/receiptInfo"
import Order from "@/views/crm/md/project/components/order.vue";
import WorkLog from "./components/WorkLog.vue";
import ProblemSummary from "./components/ProblemSummary.vue";
import {parseTime} from "@/utils/ruoyi";
import {mapGetters} from 'vuex'

export default {
  name: "MarketOrderDetailView",
  dicts: ['sys_edu_order_status'],
  components: {Order, ProblemSummary, WorkLog},
  data() {
    return {
      env: process.env.VUE_APP_STATIC_API || '',
      // 工单数据
      workorderInfo: {},
      // 请求参数
      queryParams: {
        id: null,
      },
      // tabs的标识
      activeName: '1',
      // 选择负责人与协同人的弹窗
      userVisible: false,
      // 复制的工单信息
      form: {},
      // 用户信息列表
      userList: [],
      // 校验规则
      rules: {
        principalId: [
          {required: true, message: '请选择负责人', trigger: 'change'}
        ],
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 回执信息
      receiptInfo: {},
      // 评分颜色过渡
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
    }
  },
  created() {
    this.queryParams.id = +this.$route.query.workorderId ?? null
    this.getList()
    this.getUserinfo()
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  methods: {
    async getDataInfo() {
      const res = await getDataInfoApi({
        workorderId: this.workorderInfo.id ?? 0
      })
      if (res.code === 200) {
        const row = res.data.list[0]

        let synergyIds = []
        if(typeof row?.synergyIds === 'string') {
          synergyIds = (row?.synergyIds ?? "").split(',').filter(i => i) ?? []
        } else {
          synergyIds = (row?.synergyIds ?? []).map(i => +i)
        }

        this.receiptInfo = {
          ...row,
          synergyIds
        }
      }
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 工单接受
    handleAccept() {
      this.uploadWorkorder('进行中')
    },
    // 工单完成
    handleComplete() {
      this.uploadWorkorder("已完成")
    },
    // 继续工单
    handleContinue() {
      this.uploadWorkorder("进行中")
    },
    // 确定修改
    handleUpload(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 更新工单
          await this.uploadWorkorder("已指派")
          // 关闭弹窗
          this.userVisible = false
        }
      })
    },
    // 更新工单
    async uploadWorkorder(status) {
      const payload = {
        ...this.form,
        status,
        finishTime: status === '已完成' ? parseTime(new Date().getTime()) : this.form.finishTime,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        // 更新数据
        this.getList()
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 获取用户列表
    async getUserList() {
      const response = await listUser({
        pageSize: 500
      }).catch(() => {
      })

      this.userList = (response.rows ?? []).filter(i => !i.admin)
    },
    // 转派的回调
    async handleChange() {
      // 打开弹窗
      await this.getUserList()
      // this.form = { ...this.workorderInfo }
      this.userVisible = true
      // 选择负责人和协同人
      // 确定修改
      // 更新数据
    },
    // 切换标签的回调
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    // 获取数据
    async getList() {
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        const list = res.data.list ?? []
        this.workorderInfo = list[0] ?? {}
        this.form = {...list[0]} ?? {}
        this.getDataInfo()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;

  .flex {
    display: flex;
  }

  .flex-1 {
    flex: 1 1 0%;
  }

  .items-center {
    align-items: center;
  }

  .justify-end {
    justify-content: end;
  }

  .cus_text {
    & > div {
      margin: 10px auto;

      & > span:first-child {
        display: inline-block;
        width: 120px;
        font-weight: bolder;
        text-align: justify;
        text-align-last: justify;
        margin-right: 8px;
      }
    }
  }
}
</style>
